package com.fivestar.pmanager.core.util;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 通用工具类
 *
 * @author admin
 */
public class ToolUtil
{
    private static final Logger logger = LoggerFactory.getLogger(ToolUtil.class);
    
    /**
     * 取得request对象
     * 
     * @return
     * @throws
     */
    public static HttpServletRequest getRequest()
    {
        return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
    }
    
    /**
     * 格式化文件下载名称
     *
     * @return
     * @throws
     */
    public static String formatDowanloadFileName(String fileName)
    {
        try
        {
            if (isIE()) 
            {  
                fileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");
            } 
            else 
            {  
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
        }
        catch (UnsupportedEncodingException e)
        {
            LoggerHelper.logError(logger, e);
        }  
        
        return fileName;
    }
    
    
    /**
     * 判断当前请求使用的浏览器，支持判断ie、safari、chrome、firefox、360se、opr、opera
     *
     * @return
     * @throws
     */
    public static boolean isIE()
    {
        String lowerUserAgent = getRequest().getHeader("User-Agent").toLowerCase();
        return !(lowerUserAgent.contains("chrome") || lowerUserAgent.contains("safari") || lowerUserAgent.contains("firefox") || lowerUserAgent.contains("360se") || lowerUserAgent.contains("opera") || lowerUserAgent.contains("opr"));
    }
    
    
    /**
     * 判断文件是否是图片
     *
     * @param objName 图片名
     * @return
     * @throws
     */
    public static boolean isImage(String objName)
    {
        String suffix = objName.substring(objName.lastIndexOf(".") + 1);
        //如果图片路径为空，则返回false
        if(CodeHelper.isNullOrEmpty(suffix)) return false;
        
        return "jpg,jpeg,gif,png".contains(suffix.toLowerCase());
    }
}
